﻿Imports TwitterModel
Imports System.Drawing
Imports System.Drawing.Imaging
Imports System.IO
Imports System.Xml
Imports System.Drawing.Drawing2D
Imports System.Diagnostics


Partial Class showtweet
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim mac As String = Request.Item("m")
        Dim ex As String = Request.Item("ex")
        Dim id As String = Request.Item("id")

        If Not String.IsNullOrEmpty(mac) AndAlso Not String.IsNullOrEmpty(ex) AndAlso Not String.IsNullOrEmpty(id) Then


            Dim ctx As New TwitterEntities

            Dim tweet As Tweet = ctx.Tweets.Include("Searches").FirstOrDefault(Function(t) (t.Id = id))
            Dim tweets = tweet.Searches.FirstOrDefault(Function(s) (s.Mac = mac And s.Expression = ex)).Tweets().OrderByDescending(Function(t) (t.Id)).ToArray


            Dim i = Array.IndexOf(tweets, tweet)
            Dim j = tweets.Count

            Dim model As String = Helper.GetSnomModel(Request.UserAgent)

            Dim b As Bitmap = GetSnomImage(model, tweet, i, j)

            Dim base64 As String = String.Empty
            If Not IsNothing(b) Then

                Dim fn As String = Path.GetTempPath + Path.GetFileNameWithoutExtension(Path.GetRandomFileName()) + ".bmp"
                If model = "370" Then
                    BitmapToGray8(b, fn)
                Else
                    b.Save(fn)
                End If

                Dim bytes() As Byte = File.ReadAllBytes(fn)
                File.Delete(fn)

                base64 = Convert.ToBase64String(bytes)

            End If

            Dim fTweet As Tweet = tweets(0)
            Dim fLabel As String = IIf(i = 0, " ", "First")

            Dim lTweet As Tweet = tweets(tweets.Count - 1)
            Dim lLabel As String = IIf(i = tweets.Count - 1, " ", "Last")

            Dim pTweet As Tweet
            Dim pLabel As String
            If i > 0 Then
                pTweet = tweets(i - 1)
                pLabel = "Previous"
            Else
                pTweet = fTweet
                pLabel = " "
            End If

            Dim nTweet As Tweet
            Dim nLabel As String

            If i < tweets.Count - 1 Then
                nTweet = tweets(i + 1)
                nLabel = "Next"
            Else
                nTweet = lTweet
                nLabel = " "
            End If

            Dim xml = <SnomIPPhoneImage>
                          <LocationX>0</LocationX>
                          <LocationY>0</LocationY>
                          <Data encoding="base64"><%= base64 %></Data>
                          <SoftKeyItem>
                              <Name>F1</Name>
                              <Label><%= fLabel %></Label>
                              <URL><%= Helper.TweetDetailUrl(Page, mac, ex, fTweet.Id) %></URL>
                          </SoftKeyItem>
                          <SoftKeyItem>
                              <Name>F2</Name>
                              <Label><%= pLabel %></Label>
                              <URL><%= Helper.TweetDetailUrl(Page, mac, ex, pTweet.Id) %></URL>
                          </SoftKeyItem>
                          <SoftKeyItem>
                              <Name>UP</Name>
                              <Label><%= pLabel %></Label>
                              <URL><%= Helper.TweetDetailUrl(Page, mac, ex, pTweet.Id) %></URL>
                          </SoftKeyItem>
                          <SoftKeyItem>
                              <Name>F_UP</Name>
                              <Label><%= pLabel %></Label>
                              <URL><%= Helper.TweetDetailUrl(Page, mac, ex, pTweet.Id) %></URL>
                          </SoftKeyItem>
                          <SoftKeyItem>
                              <Name>LEFT</Name>
                              <Label><%= pLabel %></Label>
                              <URL><%= Helper.TweetDetailUrl(Page, mac, ex, pTweet.Id) %></URL>
                          </SoftKeyItem>
                          <SoftKeyItem>
                              <Name>F3</Name>
                              <Label><%= nLabel %></Label>
                              <URL><%= Helper.TweetDetailUrl(Page, mac, ex, nTweet.Id) %></URL>
                          </SoftKeyItem>
                          <SoftKeyItem>
                              <Name>DOWN</Name>
                              <Label><%= nLabel %></Label>
                              <URL><%= Helper.TweetDetailUrl(Page, mac, ex, nTweet.Id) %></URL>
                          </SoftKeyItem>
                          <SoftKeyItem>
                              <Name>F_DOWN</Name>
                              <Label><%= nLabel %></Label>
                              <URL><%= Helper.TweetDetailUrl(Page, mac, ex, nTweet.Id) %></URL>
                          </SoftKeyItem>
                          <SoftKeyItem>
                              <Name>RIGHT</Name>
                              <Label><%= nLabel %></Label>
                              <URL><%= Helper.TweetDetailUrl(Page, mac, ex, nTweet.Id) %></URL>
                          </SoftKeyItem>
                          <SoftKeyItem>
                              <Name>F4</Name>
                              <Label><%= lLabel %></Label>
                              <URL><%= Helper.TweetDetailUrl(Page, mac, ex, lTweet.Id) %></URL>
                          </SoftKeyItem>
                          <SoftKeyItem>
                              <Name>CANCEL</Name>
                              <Label>Back to list</Label>
                              <URL><%= Helper.TweetsListUrl(Page, mac, ex, tweet.Id) %></URL>
                          </SoftKeyItem>
                          <SoftKeyItem>
                              <Name>ENTER</Name>
                              <Label>Back to list</Label>
                              <URL><%= Helper.TweetsListUrl(Page, mac, ex, tweet.Id) %></URL>
                          </SoftKeyItem>
                      </SnomIPPhoneImage>

            Response.ContentType = "text/xml"
            Response.Write(xml)
            Response.End()
        Else
            Response.Redirect(Helper.TweetsListUrl(Page, "0000000000", "", ""))
        End If


    End Sub

    Public Function GetSnomImage(ByVal model As String, ByVal tweet As Tweet, ByVal i As Integer, ByVal j As Integer) As Bitmap

        Dim IsValidModel As Boolean = True

        Dim space As Integer = 5

        Dim x As Integer = 0
        Dim y As Integer = 0 '23
        Dim w As Integer = 0
        Dim h As Integer = 0

        Dim avatar_h As Integer = 0
        Dim avatar_w As Integer = 0

        Dim backcolor As Color = Color.Blue
        Dim fontcolor As Color = Color.White

        Dim FontSizeTitle1 As Integer = 0
        Dim FontSizeTitle2 As Integer = 0
        Dim FontSizeMsg As Integer = 0

        Dim Footer_h As Integer = 0
        Dim author2_h As Integer = 20

        Select Case model
            Case 370
                Footer_h = 14
                w = 240
                h = 128 - Footer_h
                avatar_h = 30
                avatar_w = 30
                backcolor = Color.Black
                FontSizeTitle1 = avatar_h * 0.6
                FontSizeMsg = 10
                space = 1
                author2_h = 10
                FontSizeTitle2 = 8
            Case 820, 821
                Footer_h = 30
                w = 320
                h = 240 - Footer_h
                avatar_h = 48
                avatar_w = 48
                FontSizeTitle1 = avatar_h * 0.6
                author2_h = 10
                FontSizeTitle2 = 10
                FontSizeMsg = 15
            Case 870
                w = 480
                h = 272
                avatar_h = 60
                avatar_w = 60
                FontSizeTitle1 = avatar_h * 0.6
                FontSizeTitle2 = 10
                FontSizeMsg = 18
            Case Else
                IsValidModel = False
        End Select

        Dim b As Bitmap = Nothing
        If IsValidModel Then
            b = New Bitmap(w, h)
            Using g As Graphics = Graphics.FromImage(b)
                Dim r As Rectangle
                Dim sb As SolidBrush
                Dim f As Font
                Dim sf As StringFormat
                Dim s As String

                ' Cadre général
                r = New Rectangle(0, 0, w, h)
                sb = New SolidBrush(backcolor)
                g.FillRectangle(sb, r)

                ' Cadre Avatar
                g.DrawImage(tweet.Bitmap, space, space, avatar_w, avatar_h)

                ' Cadre Author 1
                r = New Rectangle(avatar_w + 2 * space, space, w - avatar_w - 3 * space, avatar_h)
                g.FillRectangle(sb, r)

                f = New Font("Times New Roman", FontSizeTitle1, FontStyle.Bold)
                s = tweet.UserName
                sf = New StringFormat
                sf.Alignment = StringAlignment.Near
                sf.LineAlignment = StringAlignment.Center
                sb = New SolidBrush(fontcolor)
                g.DrawString(s, f, sb, r, sf)

                ' Cadre Tweet
                r = New Rectangle(space, avatar_h + 2 * space, w - 2 * space, h - avatar_h - author2_h - 4 * space)
                sb = New SolidBrush(fontcolor)
                g.FillRectangle(sb, r)

                f = New Font("Times New Roman", FontSizeMsg, FontStyle.Italic)
                s = tweet.Msg
                sb = New SolidBrush(backcolor)
                g.DrawString(s, f, sb, r)

                ' Cadre Author 2
                r = New Rectangle(space, h - space - author2_h, w - 2 * space, author2_h)
                sb = New SolidBrush(backcolor)
                g.FillRectangle(sb, r)

                f = New Font("Times New Roman", FontSizeTitle2, FontStyle.Bold)
                s = String.Format("by {0} @ {1}", tweet.UserAlias, tweet.PublishDate)
                sf = New StringFormat
                sf.Alignment = StringAlignment.Near
                sf.LineAlignment = StringAlignment.Center
                sb = New SolidBrush(fontcolor)
                g.DrawString(s, f, sb, r, sf)

                ' Cadre Index
                s = String.Format("{0}/{1}", i + 1, j)
                sf = New StringFormat
                sf.Alignment = StringAlignment.Far
                sf.LineAlignment = StringAlignment.Center
                g.DrawString(s, f, sb, r, sf)

            End Using

        End If
        Return b

    End Function

    Public Sub BitmapToGray8(ByVal bitmap As Bitmap, ByVal fileName As String)
        Dim ms As New MemoryStream
        bitmap.Save(ms, ImageFormat.Bmp)

        Dim bImg As New System.Windows.Media.Imaging.BitmapImage
        bImg.BeginInit()
        bImg.StreamSource = ms
        bImg.EndInit()

        Dim formatConvertedBitmap As New System.Windows.Media.Imaging.FormatConvertedBitmap()
        formatConvertedBitmap.BeginInit()
        formatConvertedBitmap.Source = bImg
        formatConvertedBitmap.DestinationFormat = System.Windows.Media.PixelFormats.Gray8
        formatConvertedBitmap.EndInit()

        Dim encoder = New System.Windows.Media.Imaging.BmpBitmapEncoder()
        encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(formatConvertedBitmap))
        Dim fs As FileStream = File.Create(fileName)
        Using fs
            encoder.Save(fs)
        End Using

    End Sub

End Class
